package com.peak.distribution.web.goods;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;

import org.springframework.core.convert.converter.Converter;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.peak.distribution.entity.goods.DisGoods;
import com.peak.distribution.vo.goods.DisGoodsPriceRuleVo;
import com.peak.distribution.vo.goods.DisGoodsVo;
import com.peak.spring.boot.api.repository.FilterParam;
import com.peak.spring.boot.api.repository.FilterParam.Operator;
import com.peak.spring.boot.api.web.JsonPage;
import com.peak.spring.boot.builder.repository.FilterParamBuilder;
import com.peak.spring.boot.builder.web.JsonBuilder;
import com.peak.spring.boot.core.mapper.BeanMapper;
import com.peak.spring.boot.core.web.BaseController;
import com.peak.spring.boot.tools.Emptys;

@RestController
@RequestMapping("/goods")
public class DisGoodsController extends BaseController<DisGoods, DisGoodsVo> {

	@PostMapping("/my/list")
	public JsonPage listMyGoods(HttpServletRequest request) {
		// 只查询上架的商品
		return listGoods(request, new FilterParam("status", Operator.EQ, true));
	}
	
	@PostMapping("/admin/list")
	public JsonPage listAdminGoods(HttpServletRequest request) {
		// 只查询上架的商品
		return listGoods(request, null);
	}

	private JsonPage listGoods(HttpServletRequest request, FilterParam filterParam) {
		FilterParamBuilder builder = FilterParamBuilder.create().parseRequest(request);
		List<FilterParam> filterParams = builder.filters();
		if (Emptys.isNotEmpty(filterParam)) {
			filterParams.add(filterParam);
		}
		PageRequest pageRequest = builder.pageRequest();
		beforeList(request, filterParams, pageRequest);
		Page<DisGoods> page = baseManager.findPage(filterParams, pageRequest);
		// 把goods的转换实现了
		Page<Map<String, Object>> voPage = page.map(new Converter<DisGoods, Map<String, Object>>() {

			@Override
			public Map<String, Object> convert(DisGoods source) {
				Map<String, Object> vo = BeanMapper.map(source, DisGoodsVo.class);
				List<Map<String, Object>> priceRuleVos  = source.getRules().stream().map(p -> BeanMapper.map(p, DisGoodsPriceRuleVo.class)).collect(Collectors.toList());
				vo.put("rules", priceRuleVos);
				return vo;
			}
		});
		JsonPage json = JsonBuilder.page().success().page(voPage).build();
		json = afterList(json);
		return json;
	}
}
